import React, { useEffect, useState } from "react";
import { Modal, Form, Row, Col, InputNumber, Space, Button, Input, DatePicker } from "antd";
import { modalPropsType } from "@/constants/types";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import "./index.less";
import { orderReceiptOrder } from "../../services";
import XlSelect from "@/components/Form/XlSelect";
import dayjs from "dayjs";
import { useRequest } from "ahooks";
import { fetchDomesticWhOptions } from "@/pages/BasicInfo/services";

const { Item } = Form;
const rules = [{required: true, message: '此项必填'}];
const initValue = {receiptDetails: [{}]};

const WarehouseEntryUpdate = ({visible, onCancel, onSubmit, title, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const [info, setInfo] = useState<any>(null);
  const {data: warehouseList} = useRequest(fetchDomesticWhOptions);
  const receiptDetails = Form.useWatch("receiptDetails", form);

  const search = async () => {
    const res = await orderReceiptOrder({id: currentRow?.id});
    setInfo(res || {});
    if (res?.receiptDetails?.length > 0) {
      form.setFieldsValue({
        inWhTime: res?.inWhTime ? dayjs(res?.inWhTime) : undefined,
        cwhCode: res?.cwhCode,
        remark: res?.remark,
        receiptDetails: res?.receiptDetails?.map((v: any) => ({
          ...v,
        }))
      });
    } else {
      form.setFieldsValue({
        ...initValue
      });
    }
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      orderId: currentRow?.id,
      receiptId: info?.receiptId,
      inWhTime: res?.inWhTime?.format("YYYY-MM-DD HH:mm:ss"),
      cwhCode: res?.cwhCode,
      cwhName: warehouseList?.find((v: any) => v?.code === res?.cwhCode)?.name,
      remark: res?.remark,
      receiptDetails: res?.receiptDetails?.map((v: any) => ({
        length: v?.length,
        width: v?.width,
        height: v?.height,
        pieces: v?.pieces,
        weight: v?.weight,
      }))
    });
  }

  useEffect(() => {
    if (currentRow?.id) {
      search();
    }
  }, [currentRow?.id]);


  useEffect(() => {
    if (receiptDetails?.length > 0) {
      const volAndWeight = receiptDetails?.reduce((p: {vol: number, weight: number}, v: any) => {
        return {
          vol: p.vol + ((v?.width || 0) * (v?.height || 0) * (v?.length || 0) * (v?.pieces || 0)),
          weight: p.weight + (v?.weight || 0)
        }
      }, {vol: 0, weight: 0});
      form.setFieldsValue({
        totalVol: (volAndWeight?.vol / 1000000).toFixed(2),
        totalWeight: Number(volAndWeight?.weight).toFixed(2)
      });
    } else {
      form.setFieldsValue({
        totalWeight: 0,
        totalVol: 0
      });
    }
  }, [JSON.stringify(receiptDetails), JSON.stringify(info)])

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="1400px"
    >
      <Form form={form} className="modal-form-padding" initialValues={initValue}>
        <Row>
          <Col span={12}>
              <Item label="业务时间" name="inWhTime" rules={rules} labelCol={{span: 4}}>
                <DatePicker style={{width: 550}} showTime />
              </Item>
          </Col>
          <Col span={12}>
            <Item label="入仓仓库" name="cwhCode" rules={rules} labelCol={{span: 4}}>
              <XlSelect
                allowClear
                options={warehouseList}
                dataLabel="name"
                dataValue="code"
              />
              </Item>
          </Col>
        </Row>
        <div className="xl-self-table">
          <div className="thead">
            <Row className="tr">
              <Col span={4}>
                <div className="th">箱数</div>
              </Col>
              <Col span={4}>
                <div className="th">长/CM</div>
              </Col>
              <Col span={4}>
                <div className="th">宽/CM</div>
              </Col>
              <Col span={4}>
                <div className="th">高/CM</div>
              </Col>
              <Col span={3}>
                <div className="th">对应重量</div>
              </Col>
              <Col span={3}>
                <div className="th">对应体积</div>
              </Col>
              <Col span={2}>
                <div className="th">操作</div>
              </Col>
            </Row>
          </div>
          <div className="tbody">
            <Form.List name="receiptDetails">
              {(fields, { add, remove }) => (
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {fields.map((field, fieldIndex) => (
                    <Row className="tr" key={field.name}>
                      <Item noStyle hidden name={[field.name, 'id']}>
                        <Input />
                      </Item>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'pieces']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'length']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'width']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'height']} rules={rules}>
                            <InputNumber style={{width: 200}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={3}>
                        <div className="td">
                          <Item noStyle name={[field.name, 'weight']} rules={rules}>
                            <InputNumber style={{width: 130}} />
                          </Item>
                        </div>
                      </Col>
                      <Col span={3}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["receiptDetails", field.name]);
                              const vol = (curr?.width || 0) * (curr?.height || 0) * (curr?.length || 0) * (curr?.pieces || 0);
                              return (
                                <InputNumber value={(vol / 1000000).toFixed(2)} disabled style={{width: 130}} />
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                      <Col span={2}>
                        <div className="td">
                          <Space>
                            <Button type="primary" onClick={() => add({isDefault: false})} icon={<PlusOutlined/>}></Button>
                            {fieldIndex > 0 && <Button type="primary" onClick={() => remove(field.name)} icon={<MinusOutlined/>}></Button>}
                          </Space>
                        </div>
                      </Col>
                    </Row>
                  ))}
                </div>
              )}
            </Form.List>
          </div>
        </div>
        <Row style={{marginTop: 30}}>
          <Col span={12}></Col>
          <Col span={6}>
            <Item name="totalWeight" label="总重量">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
          <Col span={6}>
            <Item name="totalVol" label="总体积">
              <InputNumber style={{width: 200}} disabled />
            </Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Item name="remark" label="备注" labelCol={{span: 2}}>
              <Input.TextArea rows={3} />
            </Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}
export default WarehouseEntryUpdate;